package com.ziyia.a8_4_1;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;

public class MainActivity2 extends AppCompatActivity {

    private GestureDetector detector;

    private ImageView imageView;

    private int width, height;

    private Bitmap bitmap;

    private float currentScale = 1.0f;

    private Matrix matrix;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        detector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener(){
            private static final String TAG = "--------";

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

                float vx = velocityX > 4000 ? 4000f : velocityX;
                vx = velocityX < -4000 ? -4000f : velocityX;
                currentScale += currentScale * vx / 4000.0f;
                currentScale = currentScale > 0.1 ? currentScale : 0.1f;
                currentScale = currentScale > 10 ? 10f : currentScale;
                matrix.reset();

                Log.d(TAG, "onFling() called with: currentScale = [" + currentScale + "]");
                matrix.setScale(currentScale, currentScale, 150f, 200f);
                BitmapDrawable tmp = (BitmapDrawable) imageView.getDrawable();

                if (!tmp.getBitmap().isRecycled()) {
                    tmp.getBitmap().recycle();
                }
                Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                imageView.setImageBitmap(bitmap2);
                return true;
            };

        });

        matrix = new Matrix();
        imageView = findViewById(R.id.show);
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.image));

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return detector.onTouchEvent(event);
    }
}